package com.xiaowu.datajpa.service;
import com.xiaowu.datajpa.dao.TeacherRepository;
import com.xiaowu.datajpa.entity.Teacher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class TeacherSercvice {
    @Autowired
    private TeacherRepository teacherRepository;
    /**
     * 查询所有老师
     * @return
     */
    public List<Teacher> findAll(){
        return teacherRepository.findAll();
    }

    /**
     * 根据id查询老师
     * @param id
     * @return
     */
    public Teacher findById(Integer id){
        return teacherRepository.findById(id).orElse(null);
    }

    /**
     * 根据工号查询老师
     * @param teachernum
     * @return
     */
    public Teacher findByTeachernum(String teachernum){
        return teacherRepository.findByTeachernum(teachernum);
    }
    /**
     * 根据名称查询老师
     * @param name
     * @return
     */
    public List<Teacher> findByNameLike(String name){
        return teacherRepository.findByNameLike(name);
    }

    /**
     * 根据名称和密码查询老师
     * @param name
     * @param password
     * @return
     */
    public List<Teacher> findByNameAndPassword(String name,String password){
        return teacherRepository.findByNameAndPassword(name,password);
    }

    /**
     * 新增老师
     * @param teacher
     */
    public Teacher insert(Teacher teacher){
    	return teacherRepository.saveAndFlush(teacher);
    }

    /**
     * 修改老师
     * @param teacher
     */
    public Teacher update(Teacher teacher){
    	return teacherRepository.saveAndFlush(teacher);
    }

    /**
     * 删除老师
     * @param id
     */
    public void delete(Integer id){
    	teacherRepository.deleteById(id);
    }

    /**
     * 找出工号最大的教师（要求比较前4位，即年份最大的）
     * @return
     */
    public List<Teacher> findMaxTeacherNum(){
        List<Teacher> teachers = findAll();
        teachers.sort((o1, o2) -> o2.getTeachernum().compareTo(o1.getTeachernum()));
        String max = teachers.get(0).getTeachernum().substring(0, 4);
        List<Teacher> teacherList = teachers.stream()
                                            .filter(teacher -> teacher.getTeachernum().substring(0, 4).equals(max))
                                            .collect(Collectors.toList());
        return teacherList;
    }
}
